/*
 * 错误处理约定：
 * 错误分成两类：serviceExceps（业务层异常）、msgs（表单验证异常）和errors（其他异常或错误）
 * 格式(json)：{serviceExceps:"...",errors:"...", msgs:"..."}
 * 
 */
(function($){		
	function buildGrid(target){
		var opts = $.data(target,'dgridex').options;
		$(target).datagrid($.extend({},opts));	
		bindCRUDEvents(target,opts);
		if(opts.formDialog){
			$.extend($.fn.dialog.defaults,
				{buttons:[{
					text:'确定',
					iconCls:'icon-ok',
					plain:'true',
					handler:function(){
						submitForm(target,opts);								
					}
				},{
					text:'取消',
					iconCls:'icon-undo',
					plain:'true',
					handler:function(){
						opts.formDialog.dialog('close');
					}
				}]}	
			);
		}		
	}
	
	function bindCRUDEvents(target,opts){
		//添加事件
		if(opts.addButton)
			opts.addButton.bind('click.dgridex',function(){
				$.data(target,'dgridex').options.isAdd = true;
				if(opts.formDialog)
					opts.formDialog.dialog('open').dialog('setTitle','添加');
				onbeforeAdd(target,opts);
			});
		//修改事件
		if(opts.updateButton)
			opts.updateButton.bind('click.dgridex',function(){
				$.data(target,'dgridex').options.isAdd = false;
				var r = $(target).datagrid('getSelected');
				if(r){
					if(opts.formDialog)
						opts.formDialog.dialog('open').dialog('setTitle','修改');
					onBeforeUpdate(target,opts,r);
				}else{
					$.messager.alert('','请选择您要修改的记录！');
				}				
			});
		//删除事件
		if(opts.delButton)
			opts.delButton.bind('click.dgridex',function(){
				var r = $(target).datagrid('getSelected');
				if(r){
					del(target,opts,r);					
				}else{
					$.messager.alert('','请选择您要删除的记录！');
				}
			});
		//查询事件
		if(opts.searchButtons){
			$.each(opts.searchButtons,function(i,v){
				v.bind('click.dgridex',function(){
					search(target,opts,opts.searchUrls[i],opts.searchForms[i]);
				});
			});
		}			
	}
	
	function onbeforeAdd(target,opts){
		if(opts.editingForm){
			opts.editingForm.form('clear');
			opts.editingForm.form('load',opts.addValues);
		}
		return;
	}
	function onBeforeUpdate(target,opts,row){
		var form = opts.editingForm;
		if(form){
			form.form('clear');
			form.find('input[type="file"]').each(function(i){
				delete row[$(this).attr('name')];
			})
			form.form('load',row);
		}
		return;
	}
	function del(target,opts,row){
		
		$.messager.confirm('确认','您确实要删除该记录吗？',function(r){
			if(r){
				var rowIndex = $(target).datagrid('getRowIndex',row);
				if(opts.delUrl){
					var datas={};
					if(opts.idProperty)
						datas[opts.idProperty]  = row[opts.idProperty];
					else
						datas = row;
					$.getJSON(opts.delUrl,datas,function(d){
						handleResponseData(target,opts,d);
					});
					$(target).datagrid('deleteRow',$(target).datagrid('getRowIndex',row));
				}			
			}
		});	
		return;
	}
	function submitForm(target,opts){		
		var url = opts.isAdd ? addUrl : updateUrl;
		opts.editingForm.form('submit',{
			url:url,
			onSubmit:function(){
				 if($(this).form('validate')){
					return true;
				}else{
					return false;
				}
			},
			success:function(d){
				handleResponseData(target,opts,d);
				opts.formDialog.dialog('close');
				
				var data = '[';
				//opts.editingForm.form('load',opts.addValues);
				console.log(opts.editingForm.form.spreaderName.value);
			}
		});
	}
	function handleResponseData(target,opts,d){//d:响应数据
		d = $.parseJSON(d);
		/*console.log(opts.editingForm);
		var container;
		if(opts.formDialog){
			if(opts.formDialog.dialog('options').closed)
				container =  opts.errMsgsContainer;		
			else
				container = opts.dialogErrMsgsContainer;
		}
		if(!d || !d.result){
			showMistakes(container,'数据转换错误！');
			return;
		}else{		
			d = d.result;
			//处理响应数据			
			if(d.serviceExceps){
				//业务层出错，格式：{serviceExceps : "..."}				
				showMistakes(container,d.serviceExceps);
				return;
			}else if(d.msgs){
				//表单验证出错，格式：{ "msgs" ："..."}	
				showMistakes(container,d.msgs,opts.fieldMap);
				return;
			}else if(d.errors){
				//其他错误											
				showMistakes(container,d.errors);
				return;
			}else{
				//返回结果集，格式：{"rows":[]}
				
				$(target).datagrid('loadData',d.rows);
				opts.formDialog.dialog('close');
				return;
			}
		}*/
	}
	function showMistakes(container,msgs,map){
		var co = container.addClass('ErrorTip');
		var ot;
		var oc;
		//查看是否已经添加错误div
		var odivs = co.find('div');
		if(0 == odivs.length){
			ot = $('<div>您的请求有错误</div>').appendTo(co).addClass('ErrorTip_title');
			oc = $('<div/>').appendTo(co).addClass('ErrorTip_content');
		}else{
			ot = odivs[0];
			oc = odivs[1];
			if(oc)
				$(oc).empty();
		}
		console.log(msgs);
		if(map){
			for(var x in msgs){
				$('<div>' + map[x] + " : " + msgs[x] + '</div>').appendTo(oc);
			}
		}else{
			$('<div>' + msgs + '</div>').appendTo(oc);
		}	
		co.show();
	}
	
	function removeMistakesArea(containers){
		$.each(containers,function(i,v){
			v.hide();
		});
		return;
	}
	
	function search(target,opts,url,$form){
		$form.form('submit',{
			url:url,
			onSubmit:function(){
				//提交表单前要先验证
			},
			success:function(d){
				handleResponseData(target,opts,d);
			},
			onLoadError:function(){
				$.messager.alert('错误','数据加载失败！请刷新页面...');
				return;
			}
		});
	}
	
	
	$.fn.dgridex = function(options,param){
		if (typeof options == 'string'){
			var method = $.fn.edatagrid.methods[options];
			if (method){
				return method(this, param);
			} else {
				return this.datagrid(options, param);
			}
		}
		
		options = options || {};
		return this.each(function(){
			var state = $.data(this, 'dgridex');
			if (state){
				$.extend(state.options, options);
			} else {
				$.data(this, 'dgridex', {
					options: $.extend({}, $.fn.dgridex.defaults, $.fn.dgridex.parseOptions(this), options)
				});
			}
			buildGrid(this);
		});		
	};
	
	$.fn.dgridex.parseOptions = function(target){
		return $.extend({}, $.fn.datagrid.parseOptions(target), {
		});
	};
	
	$.fn.dgridex.defaults = $.extend({}, $.fn.datagrid.defaults,{
		idProperty:null,
		isAdd:true,//true:添加，false：修改
		formDialog:null,
		addButton:null,
		delButton:null,
		updateButton:null,
		searchButtons:null,  //eg. [$('#searchBtn1',$('#searchBtn2')]
		searchForms:null,    //eg. [$('#form1'),$('#form2')]
		searchUrls:null,     //eg. ['/xxx/xxx.action','/yyy/yyy.action']
		editingForm:null,
		addUrl:null,
		delUrl:null,
		updateUrl:null,
		errMsgsContainer:null,//在主界面中定义一个显示错误信息的标签
		dialogErrMsgsContainer:null,//在dialog中定义一个显示错误信息的标签
		fieldMap:null, //要进行服务器验证的字段
		idfieldName:null,//修改或删除时记录的id
		idfieldNames:[], //修改或删除时记录的id数组（批量删除和修改）
		addValues:null,
		onClickAddButton:function(jq,btn){},
		onClickEditBtton:function(jq,btn){},
		onClickDelButton:function(jq,btn){},
		onAdd:function(){},
		onUpdate:function(){},
		onDelete:function(){}
	});
	
	$.fn.dgridex.methods = {
		options:function(jq){
			var opts = $.data(jq[0], 'dgridex').options;
			return opts;
		}		
	};
})(jQuery);

